package cn.jekun.shop.web.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.Constants.ERP_ORDER_TYPE;
import cn.jekun.component.core.bean.RandomValidateCode;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpOrderMessage;
import cn.jekun.component.core.service.gen.ErpPaymentService;
import cn.jekun.shop.common.service.OrderService;
import cn.jekun.shop.common.service.ShopBaseAction;
import cn.jekun.shop.common.service.ShopService;
import cn.jekun.shop.web.bean.ErpOrderItem;

/**
 * 订单
 * @author Mr.Dong
 *
 */
@SuppressWarnings("serial")
public class OrderAction extends ShopBaseAction{
	@Resource(name = OrderService.BEAN_NAME)
	protected OrderService orderService;
	
	@Resource(name = ErpPaymentService.BEAN_NAME)
	protected ErpPaymentService paymentService;
	
	@Resource(name = ShopService.BEAN_NAME)
	protected ShopService shopService;
	
	private List<ErpOrderItem> orderitemslist = new ArrayList<ErpOrderItem>();
	
	public List<ErpOrderItem> getOrderitemslist() {
		return orderitemslist;
	}
	public void setOrderitemslist(List<ErpOrderItem> orderitemslist) {
		this.orderitemslist = orderitemslist;
	}
	
	private List<ErpOrderMessage> orderMessagelist=new ArrayList<ErpOrderMessage>();

	public List<ErpOrderMessage> getOrderMessagelist() {
		return orderMessagelist;
	}
	public void setOrderMessagelist(List<ErpOrderMessage> orderMessagelist) {
		this.orderMessagelist = orderMessagelist;
	}
	/**
	 * 获取从购物车选择的商品信息
	 * @return
	 */
	public String getOrderGoods(){
		JSONObject jsonObject = new JSONObject();
		try {
			//验证是否登录
			if(!isLogin()){
				return timeout();
			}
			String cartIds = request.getParameter("cartId"); //cartId、多个用,隔开
			jsonObject = orderService.getOrderGooods(this.getUserId(),cartIds);

		} catch(BusinessException e){
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}

	/**
	 * 获取支付方式
	 * @param map
	 * @return
	 */
	public String getOrderPayMentType(){

		JSONObject jsonObject = new JSONObject();;
		try {
			String cartIds = this.request.getParameter("cartIds");
			jsonObject = this.shopService.getPaymentByShopIdWeb(cartIds);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}

	/**
	 * 确认订单
	 * @return
	 */
	public String addOrder(){
		JSONObject jsonObject = new JSONObject();
		try {
			//验证是否登录
			if(!isLogin()){
				return timeout();
			}
			
			//检测验证码
			if (this.orderService.isAddOrderFrequently(this.getUserId(), this.getIp())) {//频繁下单
				String imgcode = this.request.getParameter("randomCode");//用户输入的图片验证码
				if(StringUtils.isBlank(imgcode)){
					jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
					jsonObject.put(ErrorMsg.KEY_MESSAGE, "非法访问");
					return this.writeJson(jsonObject);
				}
				String randomcodekey = (String) this.request.getSession().getAttribute(RandomValidateCode.RANDOMIMAGEKEY);//获取session的图片验证码
				if(randomcodekey==null){
					jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
					jsonObject.put(ErrorMsg.KEY_MESSAGE, "验证码已过时，请重新获取");
					return this.writeJson(jsonObject);
				}
				if(!(randomcodekey!=null && randomcodekey.trim().toLowerCase().equals(imgcode.trim().toLowerCase()))){
					jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
					jsonObject.put(ErrorMsg.KEY_MESSAGE,"验证码错误");
					return this.writeJson(jsonObject);
				}
				this.request.getSession().removeAttribute(RandomValidateCode.RANDOMIMAGEKEY);//验证通过后清除验证码
			}
			
			
			String userId = this.getUserId();
			String addressId =request.getParameter("addressId");
			String orderTypeId = ERP_ORDER_TYPE.WEB;//网站下单
			String paymentId = request.getParameter("paymentId");
			String shipTime = request.getParameter("shipTime");//送货时间
			String deliveryId = request.getParameter("deliveryId");//配送方式

			String orderStatusId ="";
			if(Constants.ERP_PAYMENT.PAYMENT_CASH_ON_DELIVERY.equals(request.getParameter("paymentId"))){ //货到付款
				orderStatusId =Constants.ERP_ORDER_STATUS.ORDER; //待发货
			}
			if(Constants.ERP_PAYMENT.PAYMENT_ONLINE.equals(request.getParameter("paymentId"))){ //在线支付
				orderStatusId =Constants.ERP_ORDER_STATUS.PAY; //待付款
			}

			jsonObject = orderService.addOrder(shipTime, addressId, userId, paymentId, orderStatusId, orderTypeId, this.orderitemslist, null, this.orderMessagelist,this.getIp(),this.getBrowser(),"",deliveryId);
			this.logService.addMallLog(this.getUserId(), 
            		this.getBrowser(), this.getIp(), "网站下单成功，消费金额，¥"+jsonObject.get("totalMoney"));//记录操作日志
     	} catch(BusinessException e){
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
			this.logService.addMallLog(this.getUserId(), 
					this.getBrowser(), this.getIp(), "网站下单失败，原因，"+jsonObject.get("message"));//记录操作日志
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);	
	}

	/**
	 * 取消订单
	 * @return
	 */
	public String cancelOrder(){

		JSONObject jsonObject = new JSONObject();
		String userId = this.getUserId();
		String orderId = request.getParameter("orderId");
		String memo = request.getParameter("memo");
		String reason = request.getParameter("reason");
		try {
			//验证是否登录
			if(!isLogin()){
				return timeout();
			}
			jsonObject = orderService.cancelOrder(userId,orderId,memo,reason);
			this.logService.addMallLog(this.getUserId(), 
					this.getBrowser(), this.getIp(), "网站取消订单成功,订单代码:"+orderId);//记录操作日志
		} catch(BusinessException e){
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
			this.logService.addMallLog(this.getUserId(), 
					this.getBrowser(), this.getIp(), "网站取消订单失败,订单代码:"+orderId);//记录操作日志
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);	
	}

	/**
	 * 获取我的订单及订单商品列表
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String  getMyOrderGoods(){

		JSONObject jsonObject = new JSONObject();
		try {
			//验证是否登录
			if(!isLogin()){
				return timeout();
			}
			formMap.put("userId", this.getUserId());
			if(!StringUtils.isBlank(request.getParameter("orderStatusId"))){
				formMap.put("orderStatusId", request.getParameter("orderStatusId"));
			}
			if(request.getParameter("beforeOrders")!=null && !"".equals(request.getParameter("beforeOrders"))){
				formMap.put("beforeOrders", request.getParameter("beforeOrders"));
			}
			jsonObject = orderService.getMyOrderGoods(request.getParameter("pageSize"),
					request.getParameter("currentPage"),formMap);
		} catch(BusinessException e){
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);	
	}


	/**
	 * 根据登录的用户，获取订单，按下单时间倒序。参数：订单类型
	 * @return
	 */
	public String getOrders(){
		JSONObject jsonObject = null;
		//验证是否登录
		if(!isLogin()){
			return timeout();
		}
		try {
			String userId = this.getUserId();//
			//			String userId = "201401062132110001492";
			String status = request.getParameter("status");//订单状态 0 全部，1 待发货，2 待收货，3 成功，4 关闭
			String currentPage = request.getParameter("currentPage");//当前页码(默认第1页)
			String pageSize = request.getParameter("pageSize");//页大小(默认每页10笔)

			int pageNumber=1,ps=10;
			try{
				pageNumber = Integer.parseInt(currentPage);
			}catch(Exception e){
				pageNumber = 1;
			}
			try{
				ps = Integer.parseInt(pageSize);
			}catch(Exception e){
				ps = 10;
			}
			page.setPageSize(ps);
			page.setPageNumber(pageNumber);

			if (status == null) {
				status = "0";
			}

			jsonObject = this.orderService.getOrders(userId,status,page);

		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);// 输出
	}

	/**
	 * 获取订单详细。参数：订单代码
	 * @return
	 */
	public String getOrder(){
		JSONObject jsonObject = null;
		//验证是否登录
		if(!isLogin()){
			return timeout();
		}
		try {

			String orderId = request.getParameter("orderId");//orderId

			jsonObject = this.orderService.getOrder(orderId);
			
			//判断用户操作订单的按钮是否出现
			ErpOrders orders = this.orderService.getOrderObject(orderId);
			
			//支付
			if(orders.getPaymentId().equals("2") && orders.getOrderStatusId().equals("5")){
				jsonObject.put("allowPayOrder", "1");
			}else{
				jsonObject.put("allowPayOrder", "0");
			}
			
			//确认收货（完成订单）
			boolean allowFinishOrder=this.orderService.allowFinishOrder(orders, cn.jekun.component.shop.service.OrderService.TYPE_USER);
			if(allowFinishOrder){
				jsonObject.put("allowFinishOrder", "1");
			}else{
				jsonObject.put("allowFinishOrder", "0");
			}
			
			
			//取消订单
			boolean allowCancelOrder=this.orderService.allowCancelOrder(orders, cn.jekun.component.shop.service.OrderService.TYPE_USER);
			if (allowCancelOrder) {
				jsonObject.put("allowCancelOrder", "1");
			}else{
				jsonObject.put("allowCancelOrder", "0");
			}
			
			//提醒商家发货
			boolean allowRemind=this.orderService.allowRemind(orders, cn.jekun.component.shop.service.OrderService.REMIND_TO_SHOP);
			if (allowRemind) {
				jsonObject.put("allowRemind", "1");
			}else{
				jsonObject.put("allowRemind", "0");
			}
			
			//拒绝收货
			boolean allowRefuse=this.orderService.allowRefuse(orders);
			if (allowRefuse) {
				jsonObject.put("allowRefuse", "1");
			}else{
				jsonObject.put("allowRefuse", "0");
			}
			
			//客服介入
			boolean allowApply=this.orderService.allowApply(orders);
			if (allowApply) {
				jsonObject.put("allowApply", "1");
			}else{
				jsonObject.put("allowApply", "0");
			}
			
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);// 输出
	}


	/**
	 * 推送支付消息到终端
	 * @return
	 */
	public String pushOrderByPayNo(){

		JSONObject jsonObject = null;

		try {
			//验证是否登录
			if(!isLogin()){
				return timeout();
			}
			String payNo = request.getParameter("payNo");
			jsonObject = this.orderService.pushOrderByPayNo(payNo);

		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);// 输出
	}
	
	
	/**
	 * 提醒商家发货
	 * @return
	 */
	public String remindToShop(){
		JSONObject jsonObject = null;
		try {
			//验证是否登录
			if(!isLogin()){
				return timeout();
			}
			String orderId = request.getParameter("orderId");
			jsonObject = this.orderService.remindToShop(orderId);
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
			
			this.logService.addMallLog(this.getUserId(),this.getBrowser(), this.getIp(), "网站用户提醒商家发货:"+orderId);//记录操作日志
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);// 输出
	}
	
	
	/**
	 * 用户对订单的操作
	 * @param userId
	 * @param orderId
	 * @param processCode
	 * @param processer
	 * @param reason
	 * @param fileUrl
	 * @param content
	 * @param channelId
	 * @return
	 */
	public String processOrder(){
		
		String userId = this.getSessionUser().getUserId();
		String orderId = request.getParameter("orderId");
		String processCode = request.getParameter("processCode");
		String processer = cn.jekun.component.shop.service.OrderService.TYPE_USER;//表示操作着是用户角色
		
		String reason=request.getParameter("reason");
		String fileUrl=request.getParameter("fileUrl");
		String content=request.getParameter("content");
		String channelId=null;
		
		JSONObject jsonObject = null;
		try {
			//验证是否登录
			if(!isLogin()){
				return timeout();
			}
			jsonObject = this.orderService.processOrder(userId, orderId, processCode, processer, reason, fileUrl, content, channelId);
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
			
			this.logService.addMallLog(this.getUserId(),this.getBrowser(), this.getIp(), "网站用户处理订单:"+orderId+","+processCode);//记录操作日志
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);// 输出
		
	}


	/**
     * 获取取消原因
     * @return
     */
    public String getReasonList(){
    	
    	String processCode=request.getParameter("processCode");
    	String orderId=request.getParameter("orderId");
    	
    	JSONObject jsonObject;
		try {
			jsonObject = this.orderService.reasonList(this.getSessionUser().getUserId(),processCode,cn.jekun.component.shop.service.OrderService.TYPE_USER, orderId);
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
    
    	return this.writeJson(jsonObject);
    }
    
    /**
	 * 获取商家配送方式
	 * @return
	 */
	public String getShopDeliveryType(){
		JSONObject jsonObject = new JSONObject();
		try {
			String shopId = this.request.getParameter("shopId");
			jsonObject = this.shopService.getShopDeliveryType(shopId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	
}
